<?php
/**
 * URL过滤器类
 *
 * @package  Core
 * @subpackage  
 * @author    kokko won<kokko313@gmail.com>
 */
class UrlFilter implements IFilter{
	/**
	 * 扩展名
	 *
	 * @var string
	 * @access private
	 */
	static $_ext = '.html';
	
	/**
	 * 分割变量
	 * 
	 * @var string
	 * @access private
	 */
	static $_varDiv = "=";
	
	/**
	 * 分割参数
	 * 
	 * @var string
	 * @access private
	 */
	static $_paramDiv = "&";

	/**
	 * base路径
	 *
	 * @var string
	 * @access private
	 * @static
	 */
	static $_base;

	/**
	 * 解析URL path
	 * 根据path路径解析url参数
	 *
	 * @param string $path
	 * @static 
	 */
	public static function parseURLPath( $path = '' ){
		if( $path == '')
			$path = !empty( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : null;
		if( empty( $path ) ) return false;
		$var = substr( $path,1 );
		$var = substr( $var,0,strripos( $var,self::$_ext ) );
		if( self::$_varDiv==self::$_paramDiv ){
			$param = explode( self::$_paramDiv,$var );
			for( $i=0;$i<count( $param ); ){
				if( isset( $param[$i+1] ) )
					$_GET[$param[$i]] = & trim( $param[$i+1] );
				else
					$_GET[$param[$i]] = null;
				$i = $i+2;
			}
		}else{
			$param = explode( self::$_paramDiv,$var );
			foreach( $param as $val ){
				$vals = @explode( self::$_varDiv,$val );
				if( empty( $vals[0] ) )
					continue;
				$values = !empty( $vals[1] ) ? trim( $vals[1] ) : null;
				$_GET[$vals[0]] = $values;
			}
		}
		$_REQUEST = array_merge($_REQUEST, $_GET);
	}

	/**
	 * 将现有的url转换为PATH
	 * 
	 * @param string $url
	 * @param bool $abs 是否自动补全绝对URL
	 *	当用index.php?id=1
	 *	?id=1
	 *	../index.php?id=1
	 *	./index.php?id=1
	 *	前面没有跟路径是，必须使用绝对URL
	 * @static 
	 */
	function convertURLToPath( $url,$abs = true ){
		//if( $abs )
		//$url = self::getAbsUrl( $url );
		$url = str_replace( "?",'/',$url );
		$url = str_replace( "=",self::$_varDiv,$url );
		$url = str_replace( "&",self::$_paramDiv,$url );
		return $url.self::$_ext;
	}

	/**
	 * 执行预过滤器
	 */
	public function preExecute(){
		self::parseURLPath();
		return true;
	}
	
	/**
	 * 执行后置过滤器
	 */
	public function afterExecute(){
		if( func_num_args()>0 ){
			$content = &func_get_arg(0);
			$scirpt = $_SERVER['SCRIPT_NAME'];
			$exp = "/<a.*?href=\"?\'?(.*?)[\"|\'| |>]/i";
			preg_match_all ( $exp,$content,$out,PREG_PATTERN_ORDER );
			$links = array_unique( $out[1] );
			foreach( $links as $val ){
				if( empty( $val ) || $val=='/' || $val=='#'|| strcasecmp($val,$scirpt)===0 )
					continue;
				if( stristr( $val,$scirpt )!==false )
					$content = str_replace( $val,$this->convertURLToPath($val),$content );
			}
			return $content;
		}
	}
}
?>